var express = require('express');
var router = express.Router();
const { userModel } = require('../module/module')
const { randomCode, sendCode } = require("../module/sendCode");//生成随机码和发送验证码
const jwt = require('jsonwebtoken')
const key = 'five_612_apitokenkey'//token加密的key
const nodemailer = require('nodemailer');

//发送验证码
router.post('/getCode/:phone', async (req, res) => {
    let { phone } = req.params;
    let code = randomCode(4);//生成4位数字随机验证码
    sendCode(phone, code, function (success) {
        if (success) {
            res.send({
                state: 200,
                msg: "短信验证码发送成功",
                code
            });
        } else {
            res.send({
                code: 400,
                msg: "短信验证码发送失败"
            });
        }
    })
})

//注册
router.post('/register', async (req, res) => {
    let { userName, phone, email } = req.body
    let user = await userModel.findOne({ userName });
    let userPhone = await userModel.findOne({ phone });
    let userEmail = await userModel.findOne({ email });
    if (userPhone) {
        //手机号已被绑定
        res.send({
            code: 400,
            msg: "该手机号已被绑定"
        });
        return
    }
    if (userEmail) {
        //手机号已被绑定
        res.send({
            code: 400,
            msg: "该邮箱已被绑定"
        });
        return
    }
    if (user) {
        //用户已经存在
        res.send({
            code: 400,
            msg: "该用户已经存在"
        });
    } else {
        //用户不存在进行注册
        userModel.create(req.body)
        res.send({
            code: 200,
            msg: "注册成功! 去登入"
        })
    }
})

//登入
router.post('/login', async (req, res) => {
    let { email, password } = req.body;
    let user = await userModel.findOne({ email, password });
    if (user) {
        //用户存在进行token返回
        const accessToken = jwt.sign({ userId: user._id }, key, { expiresIn: '1h' })
        const refreshToken = jwt.sign({ userId: user._id }, key, { expiresIn: '0.5d' })
        res.send({
            code: 200,
            msg: "登入成功",
            user,
            accessToken,
            refreshToken
        })
    } else {
        //用户不存在
        res.send({
            code: 400,
            msg: "信息错误"
        })
    }
})

//刷新token
router.get("/refresh", (req, res) => {
    const token = req.query.token;
    let userId = "";
    try {
        const userInfo = jwt.verify(token, key);
        userId = userInfo.userId;
    } catch (error) {
        //长token过期需要重新登入
        return res.status(400).send({
            status: 400,
            msg: "token 失效，请重新登录",
        });
    }
    //短token过期但事长token存在，刷新token
    const accessToken = jwt.sign({ ...userId }, key, { expiresIn: '1h' });
    const refreshToken = jwt.sign({ ...userId }, key, { expiresIn: '0.5d' });
    res.send({
        code: 200,
        accessToken,
        refreshToken,
    });
});

//使用手机号进行登入
router.post('/Phonelogin', async (req, res) => {
    let { phone } = req.body;
    let user = await userModel.findOne({ phone });
    if (user) {
        //用户存在进行token返回
        const accessToken = jwt.sign({ userId: user._id }, key, { expiresIn: '1h' })
        const refreshToken = jwt.sign({ userId: user._id }, key, { expiresIn: '0.5d' })
        res.send({
            code: 200,
            msg: "登入成功",
            user,
            accessToken,
            refreshToken
        })
    } else {
        //用户不存在
        res.send({
            code: 400,
            msg: "信息错误"
        })
    }
})

//邮箱验证
router.post('/email', async (req, result) => {
    let { email } = req.body;
    let code = (randomCode(6)) + 'Swk不要脸';//生成6位数的验证码
    //开启一个 SMTP 连接池
    var transport = nodemailer.createTransport({
        host: 'smtp.qq.com', //QQ邮箱的 smtp 服务器地址
        secure: true, //使用 SSL 协议
        secureConnection: false, //是否使用对 https 协议的安全连接
        port: 465, //QQ邮件服务所占用的端口
        auth: {
            user: '2415927967@qq.com', //开启 smtp 服务的发件人邮箱，用于发送邮件给其他人
            pass: 'tnwkmomqwcgodifa' //SMTP 服务授权码
        }
    })
    //邮箱配置
    var mailOption = {
        from: '2415927967@qq.com', //发件人
        to: email, //收件人
        subject: '招聘猫软件修改密码验证', //标题
        html: `<b>验证码为：${code}</br>请在5分钟之内完成验证</b>` //正文，可使用 HTML 格式进行渲染
    }
    //发送邮件
    await transport.sendMail(mailOption, (err, res) => {
        if (err) {//执行错误
            result.send({
                state: 400,
                msg: '发送失败,请检查邮箱是否正确',
            })
        } else {
            result.send({
                state: 200,
                msg: '发送成功',
                code
            }) //执行成功， 会返回响应体内容。
        }
        transport.close(); // 如果没用，则关闭连接池
    })
})

//使用邮箱进行修改密码
router.put('/emailReset',async(req,res)=>{
    let {email,password}=req.body;
    let user=await userModel.findOne({email});
    if(user){
        await userModel.updateOne({email},{password});
        res.send({
            code:200,
            msg:'密码修改成功!!!请继续登入'
        })
    }else{
        res.send({
            code:400,
            msg:'用户不存在'
        })
    }
})
//使用手机号进行修改密码
router.put('/phoneReset',async(req,res)=>{
    let {phone,password}=req.body;
    let user=await userModel.findOne({phone});
    if(user){
        await userModel.updateOne({phone},{password});
        res.send({
            code:200,
            msg:'密码修改成功!!!请继续登入'
        })
    }else{
        res.send({
            code:400,
            msg:'用户不存在'
        })
    }
})

//获取用户信息接口
router.get('/userInfo/:id', async (req, res) => {
    let { id } = req.params;
    let data = await userModel.findOne({ _id: id })
    res.send({
        code: 200,
        data: data
    })
})

//
module.exports = router;
